package com.bjpowernode.springboot.service.Impl;

import com.bjpowernode.springboot.dao.UserMapper;
import com.bjpowernode.springboot.entity.User;
import com.bjpowernode.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@SuppressWarnings("all")
@Service // 添加到spring容器中，否则在无法在controller层中注入
public class UserServiceImpl implements UserService {

    /**
     * 设置redis的key的过期参数
     */
    private final Long EXPIRE = 300l;
    private final TimeUnit TIME_UNIT = TimeUnit.SECONDS; // 秒

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate; // 注入redis的模板类对象，实现redis的相关操作

    @Autowired
    private UserMapper userMapper; // 注入User Bean 的mapper对象实现数据库的操作


    /**
     * 判断当前用户是否登录，即是否已经在缓存中
     * redis中的数据格式：sessionId : session
     * @param user
     * @return
     */
    @Override
    public boolean isReadyLogin(User user) {
        boolean isReady = false;
        ValueOperations<Object, Object> ops = redisTemplate.opsForValue(); // 操作key:value格式的数据（就是redis中的String类型）
        Set<Object> keys = redisTemplate.keys("sessionId"); // 获取所有的sessionId
        for (Object key : keys) {
            HttpSession session = (HttpSession) ops.get(key);
            if (session.getAttribute("username").equals(user.getUsername()) && session.getAttribute("password").equals(user.getPassword())) {
                isReady = true;
                break;
            }
        }
        return isReady;
    }

    /**
     * 判断该用户是否存在mysql中
     * @param user
     * @return
     */
    @Override
    public User isUserExist(User user) {
        User queryUser = userMapper.queryUser(user);
        return queryUser;
    }

    /**
     * 将用户信息封装的Session对象存放到redis中
     * @param session
     */
    @Override
    public void cacheSaveUser(HttpSession session) {
        String sessionId = (String) session.getAttribute("sessionId");
        redisTemplate.opsForValue().set(sessionId,session);
        redisTemplate.expire(sessionId,EXPIRE,TIME_UNIT); // 设置过期时间，即在时间之内，用户可以直接登录
    }

    /**
     * 添加用户到数据库中
     * @param user
     */
    @Override
    public void addUser(User user) {
        userMapper.addUser(user);
    }
}
